Add Two Distances (in inch-feet) System Using Structures with C++

04-11-17 Course- CPP

In this program takes two distances in inch-feet system and stores in data members of two structure variables. Then, this program calculates the sum of two distances and displays it.

Source code to add two distance using structure


#include <iostream>

using namespace std;

struct Distance{
    int feet;
    float inch;
}d1,d2,sum;

int main(){
    cout << "Enter information for 1st distance" << endl;
    cout << "Enter feet: ";
    cin >> d1.feet;
    cout << "Enter inch: ";
    cin >> d1.inch;
    cout << endl << "Enter information for 2nd distance" << endl;
    cout << "Enter feet: ";
    cin >> d2.feet;
    cout << "Enter inch: ";
    cin >> d2.inch;
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;

/* If inch is greater than 12, changing it to feet. */
    do{
        sum.inch=sum.inch-12.0;
        ++sum.feet;
    }while(sum.inch>12.0);

    cout << endl << "Sum of distances= " << sum.feet << " feet  " << sum.inch << " inch";
    return 0;
}

Output


Enter information for 1st distance
Enter feet: 12
Enter inch: 3.45

Enter information for 1st distance
Enter feet: 12
Enter inch: 9.2

Sum of distances= 25 feet  0.65 inch

 In this program, a structure Distance is defined with inch and feet as its members. Then, three variables(d1, d2 and sum) of struct Distancetype is created. Two variables(d1 and d2) are used for taking distance from user and the sum of two distance is stored in variable sum and then, displayed.